/* The example shows
  1. How to write a client program to connect to a server listening on certain port.
  2. A dedicated thread is used to read data from socket sent from the server.
  3. Two text field are used for providing host name and port number for connection.
  4. A third text field is used to send server the menu choices.
*/
import java.awt.* ;
import java.awt.event.* ;
import javax.swing.* ;
import java.io.* ;
import java.net.* ;

public class ClientSocketTest extends JFrame implements ActionListener {
   String strCmd[] = {"Connent", "Send" };
   JButton btnCmd[] = new JButton[2];
   String strJLabel[] = {"Host Address", "Port", "To Host" };
   String strText[] = {"136.168.201.112", "8900", "1" };
   JLabel lb[] = new JLabel[3];
   JPanel pl = new JPanel() ;
   JTextField tf[] = new JTextField[3];
   JTextArea  ta = new JTextArea(40, 70) ;

   ClientReader clientReader  = null;

   Socket client = null ;

   ClientSocketTest() {
	Container c = getContentPane();

	for ( int i = 0 ; i < 3; i ++ ) {
		lb[i] = new JLabel(strJLabel[i]) ;
		tf[i] = new JTextField(strText[i]);
		pl.add(lb[i]); pl.add(tf[i]); }

	for ( int i = 0 ; i < 2; i ++ ) {
		btnCmd[i] = new JButton(strCmd[i]);
		btnCmd[i].addActionListener(this) ;
		pl.add(btnCmd[i]); }
	btnCmd[1].setEnabled(false);
	c.add(pl, BorderLayout.SOUTH) ;
	ta.setFont(new Font("MONOSPACED", Font.PLAIN, 12) );
	c.add(new JScrollPane(ta), BorderLayout.CENTER) ;
	setTitle("Client Program") ;
	setSize(600, 400); setVisible(true) ;
   }

   public void actionPerformed(ActionEvent e ) {
	if ( e.getSource() == btnCmd[0] ) {
		try { client = new Socket(tf[0].getText(), 
				    Integer.parseInt(tf[1].getText()) ); 
		clientReader = new ClientReader(client, ta) ;
		clientReader.start() ;
		btnCmd[0].setEnabled(false) ;
		btnCmd[1].setEnabled(true) ;

		} catch(IOException er) { er.toString() ; }
	} else  if ( e.getSource() == btnCmd[1] ) {
			ta.setText("") ;
			try {
				PrintWriter out = new PrintWriter(client.getOutputStream(),true) ;
				out.println(tf[2].getText()) ;
			} catch( IOException er) { er.toString() ; }
	        }
   }

   public static void main( String arg[] ) {
	JFrame fm =  new ClientSocketTest() ;
	fm.addWindowListener( new WindowAdapter () {
		public void windowClosing(WindowEvent e) {
			System.exit(0); } } );
  }
}

class ClientReader extends Thread {

   Socket sk = null ;
   JTextArea ta = null ;
   
   public ClientReader ( Socket s, JTextArea a) { sk = s;  ta = a ; } 

   public void run() {
	try {
		BufferedReader in = new BufferedReader (
		   new InputStreamReader(sk.getInputStream())) ;
		String s = null;
		s = in.readLine() ;
		while ( s != null ) {
			ta.append(s + "\n");
			s = in.readLine() ;
			if ( ta.getText().length() > 0 ) 
				ta.setCaretPosition(  ta.getText().length()  - 1) ;
		}
 	} catch( IOException e ) { e.printStackTrace() ; }
   }
}
